package apuesta.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import apuesta.dto.UsuarioDto;
import apuesta.service.UsuarioService;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public Login() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/login.jsp").forward(request,
				response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter out = response.getWriter();
		
		String user = request.getParameter("usuario");
		String pass = request.getParameter("password");

		try {
			
			if (user.trim() == "" || pass.trim() == "") {
				request.setAttribute("error", "Ingrese Usuario/Password");
				request.getRequestDispatcher("/login.jsp").forward(request,
						response);
				return;
			}

			List<UsuarioDto> usuario = UsuarioService.IniciarSesion(user, pass);
			if (usuario.size() == 1) {
				HttpSession session = request.getSession(true);
				
				for(UsuarioDto u: usuario){
					session.setAttribute("id", u.getId_usuario());
					session.setAttribute("nombre", u.getApellidoPaterno() + " " + u.getApellidoMaterno() + ", "+  u.getNombres());
					session.setAttribute("username", u.getUsuario());
					session.setAttribute("tipousuario", u.getTipo_usuario().getId_tipousuario());
					
					
				}
				if(request.getParameter("cliente")!=null)
					out.write("ok");
				else
					response.sendRedirect("home");
				
			} else if (usuario.size() == 0) {
				
				if(request.getParameter("cliente")!=null){
					out.write("Usuario/Password incorrecto");
				}else{
					request.setAttribute("error", "Usuario/Password incorrecto");
					request.getRequestDispatcher("/login.jsp").forward(request,response);
				}
				
			} else {
				
				if(request.getParameter("cliente")!=null){
					out.write("Ha ocurrido un error");
				}else{
					request.setAttribute("error", "Ha ocurrido un error");
					request.getRequestDispatcher("/login.jsp").forward(request,response);
				}
				
				
			}
		} catch (Exception e) {
			System.out.println("Error: "+e);
		}

	}

}
